package com.jerry.boot.business.file;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jerry.boot.business.base.SiteInfoService;
import com.jerry.boot.business.common.CommonService;
import com.jerry.boot.business.file.pojo.FileDto;
import com.jerry.boot.core.base.ApiException;
import com.jerry.boot.core.base.JConfigureProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Objects;

@Service
public class FileServiceImpl extends ServiceImpl<FileMapper, FileEntity> implements FileService {

    @Resource
    private JConfigureProperties jConfigureProperties;

    @Resource
    private SiteInfoService siteInfoService;

    @Resource
    private CommonService commonService;

    @Override
    public FileDto upload(MultipartFile file) {
        String basePath = jConfigureProperties.getUploadPath();
        String today = DateUtil.today();
        File dir = new File(basePath + File.separator + today);
        dir.mkdirs();
        String fileType = Objects.requireNonNull(FileUtil.getSuffix(file.getOriginalFilename()));
        File dest = new File(dir, IdUtil.fastSimpleUUID() + "." + fileType);
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            throw new ApiException(103);
        }
        FileEntity fileEntity = new FileEntity();
        fileEntity.setFileSize(file.getSize());
        fileEntity.setOriginalFileName(file.getOriginalFilename());
        fileEntity.setFileName(dest.getName());
        fileEntity.setFileType(fileType);
        fileEntity.setFilePath(dest.getAbsolutePath());
        fileEntity.setCreateTime(new Date());
        fileEntity.setCreateUserId(commonService.getLoginUser().getId());
        this.save(fileEntity);
        String domain = siteInfoService.getSiteInfo().getDomain();
        String fileUrl = domain + "/api/file/" + fileEntity.getFileId();
        fileEntity.setUrl(fileUrl);
        this.updateById(fileEntity);
        return BeanUtil.copyProperties(fileEntity, FileDto.class);
    }

    @Override
    public FileDto file(Long fileId) {
        FileEntity fileEntity = this.getById(fileId);
        if (fileEntity == null) {
            throw new ApiException(104, fileId + "");
        }
        return BeanUtil.copyProperties(fileEntity, FileDto.class);
    }
}
